import { Modal, Form, message } from 'antd';
import ProForm, { ProFormText, ProFormDigit, ProFormRadio } from '@ant-design/pro-form';
import { save, update } from '@/services/system/resource/menu';
import {SystemMenuTreeSelect} from '@/components/system/resource'

const SystemMenuForm = (props) => {

  const [form] = Form.useForm();
  const { formVisible, onSubmit, onCancel, values } = props;

  const saveHandle = async (formValue) => {
    const data = await save(formValue);

    if (data.success) message.success('新建系统菜单成功!');
    else message.error('新建系统菜单失败!');
  };

  const updateHandle = async (formValue) => {
    const data = await update(formValue);

    if (data.success) message.success('修改系统菜单成功!');
    else message.error('修改系统菜单失败!');
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    const formValue = { ...values, ...fieldsValue, ...{id: values.menuId}};

    if (formValue.id) await updateHandle(formValue);
    else await saveHandle(formValue);

    onSubmit();
  }

  return (
    <Modal
      destroyOnClose
      title={values.id ? '修改系统菜单信息' : '新增系统菜单信息'}
      visible={formVisible}
      onOk={okHandle}
      onCancel={onCancel}
    >
      <ProForm 
        initialValues={values} 
        form={form} submitter={false}
        layout={'horizontal'} labelCol= { {span: 4} } wrapperCol= { {span: 20} }
      >
        <Form.Item label="上级资源" name="parentId" rules={[{ required: true, message: '请选择上级资源信息!' }]}>
          <SystemMenuTreeSelect disabledKey={values.id}/>
        </Form.Item>
        <ProFormText  name="name" label="菜单名称" rules={[{ required: true, message: '请输入菜单名称!' }, {max: 50, message: '菜单名称过长!'}]} />
        <ProFormText  name="icon" label="菜单图标" rules={[{max: 50, message: '菜单图标过长!'}]}/>
        <ProFormText  name="path" label="浏览路径" rules={[{ required: true, message: '请输入浏览路径!' }, {max: 200, message: '浏览路径过长!'}]}/>
        <ProFormText  name="component" label="组件路径" rules={[{max: 200, message: '组件路径过长!'}]}/>
        <ProFormDigit name="sort" label="菜单排序" min={1} max={10000} defaultValue={1} rules={[{ required: true, message: '请输入菜单排序!' }]}/>
        <ProFormRadio.Group  
          name="isIndex" label="是否主页" 
          options={[
            { value: 'YES', label: '是', },
            { value: 'NO', label: '否', },
          ]}
          initialValue="NO"
          rules={[{ required: true, message: '请选择是否主页!' }]}
        />
        <ProFormRadio.Group  
          name="showType" label="展示方式" 
          options={[
            { value: 'HOME', label: 'HOME', },
            { value: 'SCREEN', label: 'SCREEN', },
          ]}
          initialValue="HOME"
          rules={[{ required: true, message: '请选择展示方式!' }]}
        />
      </ProForm>
    </Modal>
  );
}

export default SystemMenuForm;